#!/bin/bash

#source /home/potter/Work/SandBox/youget/bin/activate

if [ "$#" != "2" ]; then
    echo "Usage:"
    echo "\t$0 videoName videoid``"
    echo "\t例如：$0 神话 4k6qfJsiHaQ"
    echo "\n"
    echo "\tSearch URL: http://www.soku.com/t/nisearch/%E7%A5%9E%E8%AF%9D"
    echo "\n"
    echo "\tWhat is [videoid] ??"
    echo "\t\tThat is each video of videos"
    echo "\turl : http://www.tudou.com/albumplay/4k6qfJsiHaQ/sDVLJxfXo38.html"
    echo "\tHere: videoid = 4k6qfJsiHaQ"
    # 
    # tudou.py
    exit
fi

name="$1"
video_id="$2"

type you-get
if [ "$?" != "0" ];then
    echo "Please download you-get"
    exit
fi

if [ ! -d "$name" ]; then
    mkdir $name
fi
cd $name

# videos urls
tudou.py $name $video_id
a=$(cat video.txt)

j=1
for i in $a; do
    # url
    echo "URL: "$i

    # videoName_4=$name".mp4"
    # videoName_v=$name".flv"
    if [ $j -lt 10 ]; then
        videoName_mp4=$name"-0$j"".mp4"
        videoName_flv=$name"-0$j"".flv"
    else
        videoName_mp4=$name"-$j"".mp4"
        videoName_flv=$name"-$j"".flv"
    fi

    if [ ! -f "$videoName_mp4" ] && [ ! -f "$videoName_flv" ]; then
        if [ -d "tmp" ]; then
            rm -rf tmp
        fi

        mkdir tmp
        cd tmp
        # tips
        echo "正在下载 "$name"-$j"
        you-get $i
        if [ "$?" != "0" ]; then
            rm -rf *
            cd ..
            echo "下载失败"
            j=$((j+1))
            sleep 1
            continue
        else
            cd ..
        fi
        #
        # sleep 2
        #
        test -f tmp/*.flv

        # if [ -f "$videoName_v" ]; then
        if [ "$?" == "0" ]; then
            # mv  $videoName_v $videoName_flv
            mv  tmp/* ./$videoName_flv
            echo "成功下载 $videoName_flv"
            echo ""
            sleep 1
        else
            # mv  $name".mp4" $videoName_mp4
            mv  tmp/* ./$videoName_mp4
            echo "成功下载 $videoName_mp4"
            echo ""
            sleep 1
        fi
    else
        echo "$name $j 已存在..."
        echo ""
    fi
    # rm tmpDir
    rm -rf tmp
    j=$((j+1))
    sleep 2
done

cd ..

exit
